/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.jinyao.exploit.common.base.service.impl;

import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jinyao.exploit.common.base.dao.TreeDao;
import com.jinyao.exploit.common.base.entity.TreeEntity;
import com.jinyao.exploit.common.base.service.TreeService;
import com.jinyao.exploit.common.utils.Reflections;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Service基类
 * @author ThinkGem
 * @version 2014-05-16
 */
@Transactional(readOnly = true)
public class TreeServiceImpl<D extends TreeDao<T>, T extends TreeEntity<T>> extends CrudServiceImpl<D, T> implements TreeService<T> {
	
	@Transactional(readOnly = false)
	public boolean save(T entity) {
		
		@SuppressWarnings("unchecked")
		Class<T> entityClass = Reflections.getClassGenricType(getClass(), 1);
		
		// 如果没有设置父节点，则代表为跟节点，有则获取父节点实体
		if (entity.getParentId() == null){
			entity.setParentId(Long.valueOf(0));
		}

		// 获取修改前的parentIds，用于更新子节点的parentIds
		String oldParentIds = entity.getParentIds(); 

		// 设置新的父节点串
		entity.setParentIds(entity.getParentIds() + entity.getParentId()+",");

		// 如果没有写入顺序，则默认为于其平级的排序+30
		if(entity.getSort() == null){
			// 获取@TableName的value属性，即为当前泛型传入的类的表名
			String tableName = entityClass.getAnnotation(TableName.class).value();
			// 获取父节点下排序最大的数值
			Integer maxSort = dao.getMaxSort(tableName, entity.getParentId());
			// maxSort + 30 即为本次sort
			entity.setSort(maxSort == null ? 30 : maxSort + 30);
		}

		// 保存或更新实体
		super.save(entity);

		// 更新字节点的parentIds
		QueryWrapper wrapper = Wrappers.query();
		wrapper.like("parent_ids","," + entity.getId() + ",");
		List<T> list = dao.selectList(wrapper);
		for (T e : list){
			if (e.getParentIds() != null && oldParentIds != null){
				e.setParentIds(e.getParentIds().replace(oldParentIds, entity.getParentIds()));
				preUpdateChild(entity, e);
				dao.updateById(e);
			}
		}

		return false;
	}
	
	/**
	 * 预留接口，用户更新子节前调用
	 * @param childEntity
	 */
	protected void preUpdateChild(T entity, T childEntity) {
		
	}
}
